const { literal, Op } = require("sequelize");
const Order = require("../models/Order");
const User = require("../models/User");

class OrderService {
    async addOrder(order){
        return Order.create(order);
    }
    async getOrderById(id){
        return Order.findByPk(id)
    }
    async getOrderListByPage(page, limit, keyword, sort, paymentStatus) {
        let where = {
            deleted_at: null
        }
        if (keyword) {
            where[Op.or] = [
                {
                    '$user.email$': {
                        [Op.like]: `%${keyword}%`,
                    },
                },
            ];
        }
        if (paymentStatus) {
            where.paymentStatus = paymentStatus
        }
        return Order.findAndCountAll({
            limit,
            offset: (page - 1) * limit,
            where,
            order: [['orderId', sort]],
            distinct: true,
            attributes: [
                'orderId',
                'total',
                'paymentStatus',
                [literal('`user`.`email`'), 'user.email'],
                [literal('`user`.`email`'), 'userEmail'],
                [literal('DATE_FORMAT(Order.created_at, "%Y-%m-%d %H:%i:%s")'), 'created_at'],
            ],
            include: [
                {
                    model: User,
                    attributes: []
                }
            ]
        });
    }
    async deleteOrder(orderId){
        return Order.destroy({
            where: {
                orderId
            }
        });
    }
    async getMyOrder(page, limit, orderStatus, userId) {
        let where = {
            deleted_at: null,
            userId
        }
        if (orderStatus) {
            where.orderStatus = orderStatus
        }
        return Order.findAndCountAll({
            limit,
            offset: (page - 1) * limit,
            where,
            order: [['orderId', 'DESC']],
            distinct: true,
            attributes: [
                'orderId',
                'total',
                'paymentStatus',
                [literal('DATE_FORMAT(Order.created_at, "%Y-%m-%d %H:%i:%s")'), 'created_at'],
            ],
        });
    }
    async cancelMyOrder(orderId){
        return await Order.update({
            orderStatus: 'cancelled'
        }, {
            where: {
                orderId
            }
        });
    }
}

module.exports = new OrderService;